<?php

namespace frontend\modules\CMS\controllers;

use frontend\controllers\BaseController;
use Yii;
use common\widgets\TencentPoiMarker;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use common\models\c2\entity\CmsPage;

/**
 * Default controller for the `customer` module
 */
class CmsController extends BaseController {

    public $pageModel;

    public function behaviors() {
        return [
            [
                'class' => 'yii\filters\PageCache',
                'only' => ['page'],
                'duration' => Yii::$app->settings->get('perf\cache_duration', 600),
                'enabled' => Yii::$app->settings->get('perf\cache_enable', 0),
                'variations' => [
                    \Yii::$app->language,
                    Yii::$app->request->get('seo_code'),
                    Yii::$app->request->get('page'),
                ],
                'dependency' => [
                    'class' => 'yii\caching\DbDependency',
                    'sql' => "SELECT updated_at FROM {{%cms_page}} where seo_code='" . Yii::$app->request->get('seo_code') . "' and is_released=1",
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['page', 'preview'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionPage($seo_code) {
        $this->pageModel = CmsPage::getValidPage($seo_code);

        if ($this->pageModel) {
            $this->layout = '/' . $this->pageModel->layout;
        } else {
            throw new NotFoundHttpException(Yii::t('app.c2', "Page not found."));
        }

        return $this->render('page', [
                    'pageModel' => $this->pageModel
        ]);
    }

    /**
     * Renders the index view for the module
     * @return string
     */
    public function actionPreview($seo_code) {
        $this->pageModel = CmsPage::getPreviewPage($seo_code);

        if ($this->pageModel) {
            $this->layout = '/' . $this->pageModel->layout;
        } else {
            throw new NotFoundHttpException(Yii::t('app.c2', "Page not found."));
        }

        return $this->render('page', [
                    'pageModel' => $this->pageModel
        ]);
    }

    public function getCacheKey() {
        if ($this->pageModel) {
            return $this->pageModel->getCacheKey();
        }
        return $this->action->id;
    }

}
